/**
 * 
 */
package com.lehecai.ucenter.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;

/**
 * @author chirowong
 *
 */
public class JpaQuery extends BaseQuery {
	
	public String toSelectString() {
		StringBuffer selectString = new StringBuffer();
		if(count){
			selectString.append("select count(").append(queryParam.getEntityAlias()).append(") from ").append(queryParam.getEntityName()).append(" ").append(queryParam.getEntityAlias());
		}else{
			selectString.append("select ").append(queryParam.getEntityAlias()).append(" from ").append(queryParam.getEntityName()).append(" ").append(queryParam.getEntityAlias());
		}
		return selectString.toString();
	}
	
	public String toQueryString() {
		StringBuffer queryString = new StringBuffer();
		if (queryParam.getParamsWhere() != null) {
			queryString.append(" where 1 = 1 ");
			
			for (Iterator<String> iterator = queryParam.getParamsWhere().keySet().iterator(); iterator.hasNext();) {
				String key = iterator.next();
				QueryWhere queryWhere = queryParam.getParamsWhere().get(key);
				if(queryWhere.getOperator().equals(QueryConstant.QUERY_OP_IN)) {
					queryString.append(" and ").append(queryParam.getEntityAlias()).append(".").append(queryWhere.getKey()).append(queryWhere.getOperator()).append("(").append(" :").append(key).append(")");
				}else {
					queryString.append(" and ").append(queryParam.getEntityAlias()).append(".").append(queryWhere.getKey()).append(queryWhere.getOperator()).append(" :").append(key);
				}
			}
		}
		return queryString.toString();
	}
	
	public String toOrderString() {
		StringBuffer orderString = new StringBuffer();
		if (queryParam.getOrders() != null) {
			orderString.append(" order by ");
			List<String> quesyOrderList = new ArrayList<String>();
			for (Iterator<QueryOrder> iterator = queryParam.getOrders().iterator(); iterator.hasNext();) {
				QueryOrder queryOrder = iterator.next();
				quesyOrderList.add(queryParam.getEntityAlias()+"."+queryOrder.getField()+" "+queryOrder.getOrder());
			}
			orderString.append(StringUtils.join(quesyOrderList,","));
		}
		return orderString.toString();
	}
	
	public String toGroupString(){
		return "";
	}

	@Override
	public String toSumString() {
		return null;
	}
}
